-module(tr_server).
-behaviour(gen_server).

-export([start_link/1, 
         start_link_v2/1]).

-export([init/1,
         handle_cast/2,
         handle_info/2,
         terminate/2]).

-record(state, {lsock,socket}).

start_link(LSock) ->
    gen_server:start_link(?MODULE, [LSock], []).

start_link_v2(Port) ->
    {ok, LSock} = gen_tcp:listen(Port, [{active, once}]),
    gen_server:start_link(?MODULE, [LSock], []).

init([LSock]) ->
    send(self(), listen),
    {ok, #state{lsock=LSock}}.

handle_cast(listen, #state{lsock=LSock}) ->
    %%{ok, LSock} = gen_tcp:listen(Port, [{active, once}]),
    {ok, Socket} = gen_tcp:accept(LSock),
    tr_server_sup:start_child(LSock),
    {noreply, #state{socket=Socket}}.

handle_info({tcp, _Port, Packet}, #state{socket=Socket}) ->
    io:format("~p~n", [Packet]),
    inet:setopts(Socket, [{active, once}]),
    {noreply, #state{socket=Socket}}.

terminate(_Reason, _State) ->
    ok.

send(Pid, Msg) ->
    gen_server:cast(Pid, Msg).

